package com.example.demo.Config;


import com.example.demo.model.Result;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

@ControllerAdvice
public class ResponseAdvice implements ResponseBodyAdvice {

    @Autowired
    private ObjectMapper objectMapper;

    @Override//是否支持进行统一结果返回
    public boolean supports(MethodParameter returnType, Class converterType) {
        return true;//所有类所有方法都统一返回
    }

    @SneakyThrows
    @Override//在请求正文前该怎么返回,这里的body就是目标方法
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        if(body instanceof Result<?>){//如果已经有Result封装了,直接返回body
            return body;
        }
        if(body instanceof String){//针对String类型排除,避免类型不匹配
            return objectMapper.writeValueAsString(Result.success(body));
        }
        return Result.success(body);
    }
}
